<script setup lang="ts" name="index">
import { ref, onMounted } from "vue";
import { GLTFLoader } from "bmap-three/examples/jsm/loaders/GLTFLoader";
import * as mapvthree from "mapv-three";
import * as THREE from "bmap-three";
import { Engine, FlyManager, UltraDynamicSky } from "mapv-three";
const config = {
  center: [116.389998, 39.9099206, 0],
  pitch: 60,
  zoom: 18,
};

const mixerArr = ref([]);
const prevTime = ref(Date.now());

const initMapEngine = (config) => {
  const { center, zoom, pitch } = config;
  const dom = document.getElementById("container");
  const engine = new Engine(dom, {
    rendering: {
      enableAnimationLoop: true,
    },
  });
  engine.map.setCenter(center);
  engine.map.setPitch(pitch);
  engine.map.setZoom(zoom);

  engine.rendering.useMrt = true;
  engine.rendering.bloom.enabled = true;
  engine.rendering.shadow.enabled = true;

  // 设置（提供光源）
  let sky = engine.add(new UltraDynamicSky());
  sky.time = 3600 * 13.5;

  const modelInfo = [
    {
      position: [116.38999802501954, 39.90992061915485, 0],
      heading: 10,
      pitch: 90,
    },
    {
      position: [116.39108091514326, 39.912365496915655, 0],
      heading: 180,
      pitch: 80,
    },
  ];

  const flyManager = engine.add(new FlyManager());
  const gltfLoader = new GLTFLoader();
  gltfLoader.load("/bpi/baidumap/Parrot.glb", async function (gltf) {
    const model = gltf.scene.children[0];
    for (let i = 0; i < modelInfo.length; i++) {
      const { position, heading, pitch } = modelInfo[i];
      const instance = model.clone();
      const pos = engine.map.projectPointArr(position);
      instance.rotation.x = Math.PI * 0.5;
      instance.position.set(...pos);

      const mixer = new THREE.AnimationMixer(instance);
      mixer.clipAction(gltf.animations[0]).setDuration(1).play();
      mixerArr.value.push(mixer);

      engine.add(instance);
      engine.event.markEventProxy(instance);
      engine.event.bind(instance, "click", (e) => {
        flyManager.flyTo(
          {
            zoom: 20,
            center: position,
            pitch,
            heading,
          },
          {
            duration: 1000,
          }
        );
      });
    }
  });

  engine.rendering.addBeforeRenderListener(() => {
    if (mixerArr.value) {
      const time = Date.now();
      for (let i = 0; i < mixerArr.value.length; i++) {
        mixerArr.value[i].update((time - prevTime.value) * 0.001);
      }
      prevTime.value = time;
    }
  });

  return engine;
};
onMounted(() => {
  initMapEngine(config);
});
</script>

<template>
  <div id="container"></div>
</template>

<style lang="scss">
#container {
  width: 100%;
  height: 700px;
}
</style>
